import { NInput, type InputInst } from 'naive-ui'

export default defineComponent({
  name: 'ShowOrEditInput',
  props: {
    value: {
      type: String,
      required: true,
    },
    onUpdateValue: {
      type: Function,
      required: true,
    },
  },
  setup(props) {
    const isEdit = ref(false)
    const inputValue = ref(props.value)
    const inputRef = ref<InputInst | null>(null)

    const handleOnClick = async () => {
      isEdit.value = true
      await nextTick()
      inputRef.value?.focus()
    }
    const handleChange = () => {
      props.onUpdateValue(inputValue.value)
      isEdit.value = false
    }
    return () => {
      return h(
        'div',
        {
          style: 'min-height: 22px',
          onClick: handleOnClick,
        },
        isEdit.value
          ? h(NInput, {
              ref: inputRef,
              value: inputValue.value,
              onUpdateValue: v => {
                inputValue.value = v
              },
              onChange: handleChange,
              onBlur: handleChange,
            })
          : props.value,
      )
    }
  },
})
